package com.delivery.www.servlet;

import com.alibaba.fastjson.JSON;
import com.delivery.www.constant.Constants;
import com.delivery.www.po.Comment;
import com.delivery.www.po.User;
import com.delivery.www.service.ServiceImpl.CommentServiceImpl;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

/**
 * @author 12970
 */
public class CommentServlet extends BaseServlet {
    CommentServiceImpl commentService = new CommentServiceImpl();

    /**
     * 评论
     * @param req 请求
     * @param resp 响应
     * @throws IOException 异常
     */
    public void doComment(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        PrintWriter writer = resp.getWriter();
        int storeId = Integer.parseInt(req.getParameter("storeId"));
        User user = (User) req.getSession().getAttribute(Constants.USER_SESSION);
        String content = req.getParameter("content");
        boolean b;
        if (!"".equals(req.getParameter(Constants.COMMENT_ID))) {
            int commentId = Integer.parseInt(req.getParameter("commentId"));
            b = commentService.doComment(storeId, user.getUserId(), content, commentId, user.getIdentity());
        } else {
            b = commentService.doComment(storeId, user.getUserId(), content, 0, user.getIdentity());
        }
        if (b) {
            writer.print("ok");
        } else {
            writer.print("error");
        }
    }

    /**
     * 删除评论
     * @param req 请求
     * @param resp 响应
     * @throws IOException 异常
     */
    public void deleteComment(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        PrintWriter writer = resp.getWriter();
        int storeId = Integer.parseInt(req.getParameter("storeId"));
        int commentId = Integer.parseInt(req.getParameter("commentId"));
        boolean b = commentService.deleteComment(commentId, storeId);
        if (b) {
            writer.print("ok");
        } else {
            writer.print("error");
        }
    }

    /**
     * 查询评论
     * @param req 请求
     * @param resp 响应
     * @throws IOException 异常
     */
    public void selectComment(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        PrintWriter writer = resp.getWriter();
        int storeId = Integer.parseInt(req.getParameter("storeId"));
        List<Comment> comments = commentService.getComment(storeId);
        writer.print(JSON.toJSONString(comments));
    }
}
